package com.woniuxy.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.woniuxy.dao.GymCoachDao;
import com.woniuxy.dao.MessageDao;
import com.woniuxy.dao.OrdersDao;

import com.woniuxy.dao.SimpleUserDao;
import com.woniuxy.entity.GymCoach;

import com.woniuxy.dao.WalletDao;
import com.woniuxy.entity.Message;
import com.woniuxy.entity.Orders;
import com.woniuxy.entity.PageBean;
import com.woniuxy.entity.Wallet;
import com.woniuxy.service.MessageService;
import com.woniuxy.util.CommonUtil;
/**
 * 
 * @author lishuwei&曾令忠
 *
 */
@Service
public class MessageServiceImpl implements MessageService {
	@Autowired
	private MessageDao messageDao;
	@Autowired
	private OrdersDao orderDao;
	@Autowired
	private GymCoachDao gymCoachDao;
	@Autowired
	private WalletDao walletDao;


	/**
	 * @author 曾令忠
	 * 添加消息
	 * sid:发送者id;aid:接受者id;content:内容
	 */
	@Override
	@Transactional
	public void addMsg(long sid, long aid, String content) {
		Message m = new Message();
		m.setUserIdSender(sid);
		m.setUserIdAccepter(aid);
		m.setMessageStatus("2");
		m.setContent(content);
		messageDao.addMessage(m);
	}

	@Override
	public List<Message> showUnread(long id) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * @author 曾令忠
	 * 分页获取未读消息
	 * status:消息状态;aid:接受者id;page:指定页码
	 */
	@Override
	public PageBean<Message> getUnreadByPage(long id, String status, int page) {
		PageBean<Message> pb = new PageBean<>();
		int pagesize = 5;
		int totalNum = messageDao.getUnreadTotalNum(id, status);
		List<Message> msges = messageDao.getUnreadByPage(id, status, (page - 1) * pagesize, pagesize);
		if (msges == null || msges.size() == 0) {
			return pb;
		}
		for (Message message : msges) {
			if(message.getOrderId()!=0) {
				String orderStatus = orderDao.getOrderStatus(message.getOrderId());
				message.setOrderStatus(orderStatus);
			}
		}
		pb.setList(msges);
		pb.setNowNum(msges.size());
		pb.setPageSize(pagesize);
		pb.setTotalNum(totalNum);
		pb.setTotalPage(totalNum % pagesize == 0 ? totalNum / pagesize : totalNum / pagesize + 1);
		pb.setNowPage(page);
		return pb;
	}

	/**
	 * @author 曾令忠
	 * 将消息状态置为已读
	 */
	@Override
	public void markToReaded(int id) {
		messageDao.updateStatus(id, "1");

	}

	/**
	 * @author 曾令忠
	 * 获取未读消息总数
	 */
	@Override
	public int getUnreadedNum(long id) {
		return messageDao.getUnreadTotalNum(id, "2");
	}

	/**
	 * @author 曾令忠
	 * 处理订单
	 * args:id,订单id;status:订单状态;role:角色信息
	 * return：1，正常；2,3，订单已处理；
	 */
	@Override
	@Transactional
	public int handleOrder(int id, String status,String role) {
		//先查询该订单的状态
		Orders orders = orderDao.getOrderById(id);
		if(!"1".equals(orders.getOrderStatus())&&!"6".equals(orders.getOrderStatus())) {
			//如果不是1，则该订单也被处理
			return 3;
		}
		// 修改订单状态
		orderDao.updateStatus(id, status);
		// 发送消息
		String content = "";
		// 需要接受者id，发送者id，发送内容
		if ("2".equals(status)) {
			
			content = "已接受您发起的" + orders.getCourseTime() + "的课程申请";
		} else if ("4".equals(status)) {
			content = "已拒绝您发起的" + orders.getCourseTime() + "的课程申请";
			
		}
		if ("2".equals(role)) {
			addMsg(orders.getUserIdCoach(),orders.getUserIdStudent(),  content);
		}else if ("1".equals(role)) {
			addMsg(orders.getUserIdStudent(), orders.getUserIdCoach(), content);
		}
		
		return 1;
	}

	@Override

	public void handleSign(int id, String status,String role) {
		GymCoach gymCoach = gymCoachDao.getGymCoachById(id);
		gymCoachDao.updateStatus(id, status);
		Message message = new Message();
		String content = "";
		// 需要接受者id，发送者id，发送内容
		if ("3".equals(status)) {
			content = "已接受您的签约申请";
		} else if ("4".equals(status)) {
			content = "已拒绝您的签约申请";
		}
		if ("2".equals(role)) {
			message.setContent(content).setMessageStatus("2").setUserIdAccepter(gymCoach.getUserIdGym())
			.setUserIdSender(gymCoach.getUserIdCoach());
		}else if("3".equals(role)) {
			message.setContent(content).setMessageStatus("2").setUserIdSender(gymCoach.getUserIdGym())
			.setUserIdAccepter(gymCoach.getUserIdCoach());
		}
		messageDao.addMessage(message);
	}

	/**
	 * @author 曾令忠
	 * 提现
	 * id:wallet id；num:金额
	 */
	@Override
	public boolean outMoneyReq(int id, double num) {
		Wallet w = walletDao.getMyWallet(id);
		if(w.getBalance()<num) {
			return false;
		}
		String content = "id为:"+w.getUserId()+"的用户递交了提现申请,金额是："+num;
		addMsg(w.getUserId(), 24, content);
		return true;
	}

	/**
	 * @author 曾令忠
	 * 付款
	 * oid:订单id
	 */
	@Override
	@Transactional
	public int payOrder(Integer oid) {
		// 判断待支付用户账户余额是否充足
		Orders o = orderDao.getOrderById(oid);
		if(!"2".equals(o.getOrderStatus())) {
			return 4;
		}
		double amount = o.getPayable();
		Wallet w1 = walletDao.getMyWalletByUserId((int)o.getUserIdStudent());
		if(w1.getBalance()<amount) {
			return 3;
		}
		//支付
		Wallet w2 = walletDao.getMyWalletByUserId((int)o.getUserIdCoach());
		walletDao.deposit((int)w2.getUserId(), w2.getBalance()+amount);
		walletDao.deposit((int)w1.getUserId(), w1.getBalance()-amount);
		//更改订单状态
		orderDao.updateStatus((int)o.getId(), "3");
		//发送支付成功的消息
		String content = CommonUtil.getCurrentUser().getNickname()+"已成功支付订单id："+o.getId();
		addMsg(o.getUserIdStudent(),o.getUserIdCoach(),content);
		return 1;
		
		
	}



}
